package cn.school.common.utils.wx;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Component
public class WeiXinPayCommonUtil {

	private static final Logger logger =   LogManager.getLogger(WeiXinPayCommonUtil.class);
	
	public String getMapToXML(Map<String, String> param) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		for (Map.Entry<String, String> entry : param.entrySet()) {
			sb.append("<" + entry.getKey() + ">");
			sb.append(entry.getValue());
			sb.append("</" + entry.getKey() + ">");
		}
		sb.append("</xml>");
		return sb.toString();
	}
	
	// xml解析
		public Map doXMLParse(String strXML) throws Exception {
			Map<Object,Object> data = new HashMap<>();
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			String FEATURE = null;
			try {

				FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
				documentBuilderFactory.setFeature(FEATURE, true);

				FEATURE = "http://xml.org/sax/features/external-general-entities";
				documentBuilderFactory.setFeature(FEATURE, false);

				FEATURE = "http://xml.org/sax/features/external-parameter-entities";
				documentBuilderFactory.setFeature(FEATURE, false);

				FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
				documentBuilderFactory.setFeature(FEATURE, false);

				documentBuilderFactory.setXIncludeAware(false);
				documentBuilderFactory.setExpandEntityReferences(false);

			} catch (ParserConfigurationException e) {
				logger.error("doXMLParse ParserConfigurationException  errMessage:{}" ,e.getMessage());
			}
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
			org.w3c.dom.Document doc = documentBuilder.parse(stream);
			doc.getDocumentElement().normalize();
			NodeList nodeList = doc.getDocumentElement().getChildNodes();
			for (int idx = 0; idx < nodeList.getLength(); ++idx) {
				Node node = nodeList.item(idx);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					org.w3c.dom.Element element = (org.w3c.dom.Element) node;
					data.put(element.getNodeName(), element.getTextContent());
				}
			}
			try {
				stream.close();
			} catch (Exception ex) {
				logger.error("doXMLParse errMessage:{}" ,ex.getMessage());
			}
			return data;

		}

}
